package com.xuecheng.content.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xuecheng.base.exception.XueChengPlusException;
import com.xuecheng.content.mapper.TeachplanMapper;
import com.xuecheng.content.mapper.TeachplanMediaMapper;
import com.xuecheng.content.model.dto.BindTeachplanMediaDto;
import com.xuecheng.content.model.dto.SaveTeachplanDto;
import com.xuecheng.content.model.dto.TeachplanDto;
import com.xuecheng.content.model.po.Teachplan;
import com.xuecheng.content.model.po.TeachplanMedia;
import com.xuecheng.content.service.TeachplanService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author Mr.M
 * @version 1.0
 * @description TODO
 * @date 2023/2/14 12:11
 */
@Service
public class TeachplanServiceImpl implements TeachplanService {

    @Autowired
    TeachplanMapper teachplanMapper;

    @Autowired
    TeachplanMediaMapper teachplanMediaMapper;

    @Override
    public List<TeachplanDto> findTeachplanTree(Long courseId) {
        List<TeachplanDto> teachplanDtos = teachplanMapper.selectTreeNodes(courseId);
        return teachplanDtos;
    }

    private int getTeachplanCount(Long courseId,Long parentId){
        LambdaQueryWrapper<Teachplan> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper = queryWrapper.eq(Teachplan::getCourseId, courseId).eq(Teachplan::getParentid, parentId);
        Integer count = teachplanMapper.selectCount(queryWrapper);
        return  count+1;
    }
    @Override
    public void saveTeachplan(SaveTeachplanDto saveTeachplanDto) {
        //通过课程计划id判断是新增和修改
        Long teachplanId = saveTeachplanDto.getId();
        if(teachplanId ==null){
            //新增
            Teachplan teachplan = new Teachplan();
            BeanUtils.copyProperties(saveTeachplanDto,teachplan);
            //确定排序字段，找到它的同级节点个数，排序字段就是个数加1  select count(1) from teachplan where course_id=117 and parentid=268
            Long parentid = saveTeachplanDto.getParentid();
            Long courseId = saveTeachplanDto.getCourseId();
            int teachplanCount = getTeachplanCount(courseId, parentid);
            teachplan.setOrderby(teachplanCount);
            teachplanMapper.insert(teachplan);

        }else{
            //修改
            Teachplan teachplan = teachplanMapper.selectById(teachplanId);
            //将参数复制到teachplan
            BeanUtils.copyProperties(saveTeachplanDto,teachplan);
            teachplanMapper.updateById(teachplan);
        }

    }

    /**
     * 绑定媒资关系
     * @param bindTeachplanMediaDto
     * @return
     */
    @Transactional
    @Override
    public TeachplanMedia associationMedia(BindTeachplanMediaDto bindTeachplanMediaDto) {
        //教学计划id
        Long teachplanId = bindTeachplanMediaDto.getTeachplanId();
        Teachplan teachplan = teachplanMapper.selectById(teachplanId);
        if(teachplan==null){
            XueChengPlusException.cast("教学计划不存在");
        }
        Integer grade = teachplan.getGrade();
        if(grade!=2){
            XueChengPlusException.cast("只允许第二级教学计划绑定媒资文件");
        }
        //课程id
        Long courseId = teachplan.getCourseId();

        //先删除原来该教学计划绑定的媒资
        teachplanMediaMapper.delete(new LambdaQueryWrapper<TeachplanMedia>().eq(TeachplanMedia::getTeachplanId,teachplanId));

        //再添加教学计划与媒资的绑定关系
        TeachplanMedia teachPlanMedia = new TeachplanMedia();
        teachPlanMedia.setCourseId(courseId);
        teachPlanMedia.setTeachplanId(teachplanId);
        teachPlanMedia.setMediaFilename(bindTeachplanMediaDto.getFileName());
        teachPlanMedia.setMediaId(bindTeachplanMediaDto.getMediaId());
        teachPlanMedia.setCreateDate(LocalDateTime.now());
        teachplanMediaMapper.insert(teachPlanMedia);
        return teachPlanMedia;
    }

    /**
     * 下移课程排序
     * @param id
     */
    @Override
    public void moveDownTeachPlan(Long id) {
        changeOrder(id, false);
    }

    /**
     * 上移课程排序
     * @param id
     */
    @Override
    public void moveUpTeachPlan(Long id) {
        changeOrder(id, true);

    }
    /**
     * 更新排序字段(删除)
     */
    public void updateOrderBy(Long id) {
        Teachplan teachPlan = teachplanMapper.selectById(id);
        if (teachPlan != null) {
            LambdaQueryWrapper<Teachplan> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Teachplan::getCourseId, teachPlan.getCourseId())
                    .eq(Teachplan::getParentid, teachPlan.getParentid())
                    .gt(Teachplan::getOrderby,teachPlan.getOrderby());
            // 查询满足条件的所有数据
            List<Teachplan> teachPlans = teachplanMapper.selectList(queryWrapper);
            if (teachPlans!=null){
                for (Teachplan otherteachPlan : teachPlans) {
                    otherteachPlan.setOrderby(otherteachPlan.getOrderby()-1);
                    teachplanMapper.updateById(otherteachPlan);
                }
            }
        }
    }
    /**
     * 改变课程计划的排序
     * @param id 当前课程计划ID
     * @param isMoveUp 是否是上移操作
     */
    private void changeOrder(Long id, boolean isMoveUp) {
        // 获取当前课程计划
        Teachplan teachPlan = teachplanMapper.selectById(id);
        if (teachPlan == null) {
            return; // 课程计划不存在
        }

        // 构建查询条件以获取相邻的课程计划
        LambdaQueryWrapper<Teachplan> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Teachplan::getCourseId, teachPlan.getCourseId())
                .eq(Teachplan::getParentid, teachPlan.getParentid());

        if (isMoveUp) {
            queryWrapper.lt(Teachplan::getOrderby, teachPlan.getOrderby())
                    .orderByDesc(Teachplan::getOrderby);
        } else {
            queryWrapper.gt(Teachplan::getOrderby, teachPlan.getOrderby())
                    .orderByAsc(Teachplan::getOrderby);
        }

        // 获取相邻的课程计划
        Teachplan adjacentPlan = teachplanMapper.selectOne(queryWrapper.last("limit 1"));

        if (adjacentPlan != null) {
            // 交换orderby值
            int tempOrderby = teachPlan.getOrderby();
            teachPlan.setOrderby(adjacentPlan.getOrderby());
            adjacentPlan.setOrderby(tempOrderby);

            // 更新数据库
            teachplanMapper.updateById(teachPlan);
            teachplanMapper.updateById(adjacentPlan);
        }
    }
    /**
     * 根据课程id删除课程计划
     * @param id
     */
    @Override
    public void deleteTeachPlanById(Long id) {
        //查询课程信息
        Teachplan teachPlan = teachplanMapper.selectById(id);
        //判断课程计划是否为一级章节
        if (teachPlan.getParentid()==0){
            //查询一级章节下是否包含小节
            LambdaQueryWrapper<Teachplan> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper = queryWrapper.eq(Teachplan::getCourseId, teachPlan.getCourseId()).eq(Teachplan::getParentid,id);
            int count=teachplanMapper.selectCount(queryWrapper);
            //包含小章节，不能删除
            if (count!=0){
                XueChengPlusException.cast("课程计划信息还有子级信息，无法操作");
            }
        }
        //更新排序字段
        updateOrderBy(id);
        //删除该课程计划
        teachplanMapper.deleteById(teachPlan);
        //删除第二级小节包含的视频信息
        //根据课程id和课程计划id查询视频
        LambdaQueryWrapper<TeachplanMedia> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper = queryWrapper.eq(TeachplanMedia::getCourseId, teachPlan.getCourseId()).eq(TeachplanMedia::getTeachplanId,id);
        teachplanMediaMapper.delete(queryWrapper);
    }
}
